<template>
    <div class="item" :id="todo.id" @click="checked">
        <label class="itemLabel">
            <input type="checkbox"  @click="checked(todo.id)" v-model="todo.done"/>
            <span v-show="!todo.isEdit">{{todo.title}}</span>
            <span v-show="todo.isEdit">
                <input 
                    :value="todo.title"
                    @keyup.enter="blur(todo,$event)"
                    @blur="blur(todo,$event)" 
                    type="text" 
                    ref="inputTitle"
                />
            </span>
        </label>
        <button @click="clear(todo.id)" class="btn btn-delete">删除</button>
        <button  v-show="!todo.isEdit" @click="edit(todo)" class="btn btn-edit">编辑</button>
    </div>
</template>

<script>
import 'animate.css'
import pubsub from 'pubsub-js'

export default {
    name:"Item",
    props:['todo'],
    methods:{
        //勾选该选项
        checked(id){
            this.$bus.$emit("checkTodo",id);
        },
        //删除该选项
        clear(id){
            pubsub.publish("deleteTodo",id);
        },
        //编辑
        edit(todo){
            if(Object.prototype.hasOwnProperty.call(todo, "isEdit")){
                todo.isEdit = true;
            }else{
                this.$set(this.todo,'isEdit',true);
            }
            //API $nextTick会在下一次DOM更新后执行回调
            this.$nextTick(function(){
                //API $refs,跟HTML中同样绑定ref = inputTitle的位置实现联动。
                this.$refs.inputTitle.focus()
            })
        },
        //由编辑返回文字状态，完成更改
        blur(todo,e){
           todo.isEdit = false;
           if(!e.target.value.trim()) return alert("输入不能为空")
           this.$bus.$emit("updateTodo",todo.id,e.target.value)
        }
    }
}
</script>

<style>
    .item{
        border: 1px solid;
        box-shadow:#c8cccf 0px 4.5px 0px 0px;    
        width: 375px;
        display:block;
        height: 26px;
        border: 1px solid #c8cccf;
        border-radius: 14px;
        margin: 10px;
        padding-top:4px;
        position: relative;
    }
    .item:hover{
        background-color: whitesmoke;
    }
    .item:hover .btn{
        display: inline;
    }
    
    .btn{
        color:white;
        font-weight: 600;
        position:relative;
        right: 10px;
        top:-2px;
        height: 26px;
        width: 70px;
        border-radius: 10px;
        font-size:14px;
        border: none;
        box-shadow:rgb(192, 181, 161) 0px 0px 2px 2px;
        display: none;
        float:right;
    }
    .btn:active{
        box-shadow:rgb(192, 181, 161) 1px 1px 0px 0px;
    }
    .btn-delete{
        background-color: rgb(255, 123, 0);
    }
    .btn-edit{
        background-color: skyblue;
        margin-right:7px;
    }

    .itemLabel{
        position: absolute;
        left:10px;
    }
</style>